<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      fixed
      left-arrow
      @click-left="$router.back()"
      title="article.title"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <!-- 加载中 loading -->
    <van-loading v-if="loading" class="article-loading" />
    <!-- /加载中 loading -->
    <div class="error" v-if="is404">
      <p>文章被外星人吃掉了</p>
      <van-button @click="$router.back()">后退` </van-button>
      <van-button @click="$router.push('/')">回主页</van-button>
    </div>
    <!-- 文章详情 -->
    <div class="detail" v-else>
      <h3 class="title">{{article.title}}</h3>
      <author :author="article">
        <van-button
          round
          size="small"
          type="info"
          @click="hSwitchFollow"
        >{{ article.is_followed ? '取关' : '+ 关注'}}</van-button>
      </author>
      <div class="content">
        <div v-html="article.content"></div>
      </div>
      <van-divider>END</van-divider>
      <div class="zan">
        <van-button round size="small" hairline type="primary" plain :icon="article.attitude === 1 ? 'good-job': 'good-job-o'"
        @click="hSwitchLike">{{article.attitude === 1 ? '取消点赞' : '点赞'}}</van-button>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <van-button round size="small" hairline type="danger" plain icon="delete"
        @click="hSwitchDisLike">{{article.attitude === 0 ? '取消不喜欢' : '不喜欢'}}</van-button>
      </div>
    </div>
    <!-- /文章详情 -->
    <!-- 文章评论 -->
    <article-comment :articleId="articleId" ref="refArticleComment"></article-comment>
    <!-- 文章评论 -->
  </div>
</template>

<script>
// 引入封装的作者插件
import Author from '@/components/author'
// 引入评论列表组件
import ArticleComment from './comment'
import { getArticle, unFollowUser, followUser, deleteLike, addLike, deleteDisLike, addDisLike } from '@/api/article.js'
export default {
  name: 'ArticleIndex',
  components: {
    Author, ArticleComment
  },
  data () {
    return {
      is404: false, // 文章是否存在
      articleId: null,
      loading: true, // 控制加载中的 loading 状态
      article: {}
    }
  },
  created () {
    this.articleId = this.$route.query.id
    this.loadArticle()
  },
  // beforeRouteLeave (to, from, next) {
  //   console.log('你现在在文章详情页，你将要离开这个页面')
  //   console.log(to, from)
  //   if (to.path === '/login' && this.$store.state.tokenInfo.token) {
  //     next({ path: '/' })
  //   } else {
  //     next()
  //   }
  // },
  // 组件级别的路由守卫
  beforeRouteLeave (to, from, next) {
    if (!this.$refs.refArticleComment.content) {
      // 没有评论，没有提示，直接路由跳转
      // if (to.path === '/login' && this.$store.state.tokenInfo.token) {
      //   next({ path: '/' })
      // } else {
      //   next()
      // } // 全局拒绝回到登录页
      next()
    } else {
      // 有评论内容，要提示，直接路由跳转
      const ans = window.confirm('页面上有评论，如果离开就会丢失，你确定吗?')
      if (ans) {
        // if (to.path === '/login' && this.$store.state.tokenInfo.token) {
        //   next({ path: '/' })
        // } else {
        //   next()
        // }
        next()
      } else {
        // 页面不跳转
        next(false)
      }
    }
  },
  methods: {
    async loadArticle () {
      // 1. 设置loading
      this.loading = true
      try {
        // 2. 发请求
        const result = await getArticle(this.articleId)
        // console.log(result)
        this.article = result.data.data
        // 3. 设置loading
        this.loading = false
      } catch (err) {
        this.loading = false // 结束loading
        if (err.response && err.response.status === 404) {
          this.is404 = true
        } else {
          this.$toast.fail('文章加载失败')
        }
      }
    },
    // 如果文章是自己写的那么不能关注自己
    async hSwitchFollow () {
      try {
        const isFollowed = this.article.is_followed
        const autId = this.article.aut_id
        // 根据当前的isfollowed值来判断是关注还是取消关注 从而调用不同的方法
        if (isFollowed) {
          const result = await unFollowUser(autId)
          console.log(result)
        } else {
          const result = await followUser(autId)
          console.log(result)
        }
        // 更新视图
        // 在本地数据进行取反
        this.article.is_followed = !isFollowed
        this.$toast.success('操作成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }
    },
    // 是否取消点赞
    async hSwitchLike () {
      // 根据当前attitude来决定调用哪一个方法：
      // 如果attitude是1，即当前给文章点赞的，则点击动作就是要 取消点赞
      if (this.article.attitude === 1) {
        await deleteLike(this.article.art_id.toString())
      } else {
        await addLike(this.article.art_id.toString())
      }
      this.$toast.success('操作成功')
      // 更新视图
      // 1. 重新获取整个页面 （不采用，成本太高）
      // 2. 只更新本地的数据项（就是取反: -1 <-------> 1）
      //    采用。原因如果这个请求接口操作并没有报错，则说明后端已经把数据更改了
      //          这里视图上，直接修改就行了。
      this.article.attitude = this.article.attitude * -1
    },
    // 是否取消不喜欢
    async hSwitchDisLike () {
      // 根据当前的attitude来决定调用接口
      if (this.article.attitude === 0) {
        await deleteDisLike(this.article.art_id.toString())
        this.article.attitude = -1
      } else {
        await addDisLike(this.article.art_id.toString())
        this.article.attitude = 0
      }
      this.$toast.success('操作成功')
    }
  }
}
</script>

<style scoped lang='less'>
.article-container{
  position: absolute;
  left: 0;
  top: 0;
  overflow-y: scroll;
  width: 100%;
  height: 100%;
}
.article-loading {
  padding-top: 100px;
  text-align: center;
}
.error{
  padding-top: 100px;
  text-align: center;
}
.detail {
  padding: 50px 10px;
  .title {
    font-size: 16px;
  }
  .zan{
    text-align: center;
  }
  .author {
    padding: 10px 0;
    display: flex;
    .text {
      flex: 1;
      padding-left: 10px;
      line-height: 1.3;
      .name {
        font-size: 14px;
        margin: 0;
      }
      .time {
        margin: 0;
        font-size: 12px;
        color: #999;
      }
    }
  }
  .content {
    font-size:14px;
    overflow: hidden;
    white-space: pre-wrap;
    word-break: break-all;
    /deep/ img{
      max-width:100%;
      background: #f9f9f9;
    }
  }
}
</style>
